
import sys
from  stdtype import *
import time

class cantest:
    def __init__(me,cancom, canid , log=None ) :
        me.cancom=cancom
        if log == None:
            log=sys.stdout
        me.log=log
        me.canid=canid
        me.testid=0
        
        me.count_success=0
        me.count_fail=0
        
        starttime=int(time.time())
        me.cancom.send_msg( pack_to_list(  [ U32B( 0xff ), U32B(starttime) ] ) , me.canid )
        me.log.write('Start test {:#x}\n '.format( starttime ))

    def close(me):
        print("Total numer of tests:{}".format(me.count_success+me.count_fail)) 
        print("Success             :{}".format(me.count_success)) 
        print("FailedTotal         :{}".format(me.count_fail)) 

    def case( me, text , value ):
        me.testid+=1
        
        if value == True:
            result= 'OK  '
            code=1
            me.count_success+=1
        else:
            result= 'FAIL'
            code=0
            me.count_fail+=1
            
        me.log.write('0x{:>07x} {} {} \n'.format( me.testid,  result, text ))

        me.cancom.send_msg( pack_to_list(  [ U32B( code ), U32B(int(me.testid)) ] ) , me.canid )
   
    def __enter__(me):
        me.testid+=1
        me.cancom.send_msg( pack_to_list(  [ U32B( 0 ), U32B(int(me.testid)) ] ) , me.canid )
        return me
    
    def __exit__(me, type, value, traceback):
        me.cancom.send_msg( pack_to_list(  [ U32B( 1 ), U32B(int(me.testid)) ] ) , me.canid )
        